<?php

namespace app\common\model;

use app\common\config\cache\CacheKey;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * Class Role
 * @package app\model
 */
class Role extends ModelBase
{
    use SoftDelete;

    // 验证器
    protected $validate = \app\common\validate\Role::class;
    // 只读字段
    protected $readonly = ['id','uuid','create_time','creator'];

    /**
     * 属性修改器
     */
    public function setRulesAttr($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 属性获取器
     */
    public function getRulesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 删除缓存
     */
    public function removeCache($id)
    {
        $cacheKey = CacheKey::role()->key($id);
        cache($cacheKey, null);
    }

    /**
     * 从缓存读取role信息
     */
    public function findByCache($id)
    {
        $cacheKey = CacheKey::role()->key($id);
        $role = cache($cacheKey);
        if (!empty($role)) {
            return $role;
        }

        $role = $this->find($id);
        cache($cacheKey, $role);

        return $role;
    }

    /**
     * @param $data
     * @param $userId
     * @return Role|\think\Model
     * 新增
     */
    public function add($data, $userId)
    {
        empty($data['uuid']) && $data['uuid'] = uuid();
        $data['creator'] = $userId;
        $data['updater'] = $userId;

        validate($this->validate)->scene('add')->check($data);

        $data = $this->createda($data);

        return Role::create($data);
    }

    /**
     * @param $data
     * @param $userId
     * @return Role
     * 修改
     */
    public function edit($data, $userId)
    {
        $data['updater'] = $userId;
        validate($this->validate)->scene('edit')->check($data);
        $updateObj = Role::update($data, ['id' => $data['id'], 'uuid' => $data['uuid']]);
        $this->removeCache($data['id']);
        return $updateObj;
    }

    /**
     * @param $data
     * @param $userId
     * @return bool
     * 删除
     */
    public function del($data, $userId)
    {
        validate($this->validate)->scene('del')->check($data);
        $delFlag = false;
        Db::startTrans();
        try {
            // 先更新再删除
            Role::where('id',  $data['id'])
                ->where('uuid', $data['uuid'])
                ->save(['updater' => $userId]);

            $delFlag = Role::where(['id'=>$data['id'],'uuid'=>$data['uuid']])->find()->delete();
            $this->removeCache($data['id']);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            exception('删除失败');
        }

        return $delFlag;
    }


}
